package org.opens.zip.controller;

import cn.hutool.core.io.IoUtil;
import org.opens.util.ReadClassPathFileUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;

/**
 * 功能描述
 *
 * @author by zhangyuming
 * @date 2022/9/26
 */
@RequestMapping(value = "/zip")
@RestController
public class ZipController {

    @RequestMapping(value = "/download")
    public void download(HttpServletResponse response) {
        // 文件的存放路径
        File zipFile = ReadClassPathFileUtil.readAsFile("zip/1677484458580222.zip");
        try (
                InputStream inputStream = Files.newInputStream(zipFile.toPath());
                ServletOutputStream outputStream = response.getOutputStream()
        ) {
            // 设置响应类型
            response.setContentType("application/octet-stream;charset=UTF-8");
            // 设置响应编码
            response.setCharacterEncoding("UTF-8");

            // 设置文件名
            String filename = zipFile.getName();
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));

            // 重置response并写入流文件, 可以使用hutool的IOUtil来增强
            response.reset();

            // 写入文件流
            IoUtil.copy(inputStream, outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
